package com.hzsoft.sys.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;

import net.sf.json.JSONObject;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.hzsoft.base.entity.BJuiJSON;
import com.hzsoft.base.entity.Page;
import com.hzsoft.sys.entity.TblQuestionBank;
import com.hzsoft.sys.entity.TblTestParameter;
import com.hzsoft.sys.service.TblQuestionBankService;
import com.hzsoft.sys.service.TblTestParameterService;
import com.hzsoft.util.DateUtil;
import com.hzsoft.util.JsonUtil;

/**
 * 题库管理
 * @author Administrator
 *
 */
@Controller
@RequestMapping("/answer/tk")
public class TblQuestionBankController {
	@Autowired
	private TblQuestionBankService tblQuestionBankService;
	@Autowired
	private TblTestParameterService parameterService;
	
	
	@RequestMapping("/tkList")
	public ModelAndView showUser(@ModelAttribute TblQuestionBank bank,Model model,HttpServletRequest request,HttpServletResponse response) {
		//分页设置
		String pageCurrent = request.getParameter("pageCurrent");
		Page page =  new Page();
		if (StringUtils.isNotBlank(pageCurrent)) {
			page.setPageCurrent(Integer.parseInt(pageCurrent));
			bank.setPage(page);
		}
		
		List<TblQuestionBank> list = tblQuestionBankService.listPageBank(bank);
		
		model.addAttribute("bank",bank);
		model.addAttribute("page", bank.getPage());
		model.addAttribute("list",list);
		
		return new ModelAndView("answer/tk/tkList");
		
	}
	@RequestMapping("/parList")
	public ModelAndView parList(@ModelAttribute TblTestParameter par,Model model,HttpServletRequest request,HttpServletResponse response) {
		//分页设置
		String pageCurrent = request.getParameter("pageCurrent");
		Page page =  new Page();
		if (StringUtils.isNotBlank(pageCurrent)) {
			page.setPageCurrent(Integer.parseInt(pageCurrent));
			par.setPage(page);
		}
		
		List<TblTestParameter> list = parameterService.listPagePar(par);
		
		model.addAttribute("par",par);
		model.addAttribute("page", par.getPage());
		model.addAttribute("list",list);
		
		return new ModelAndView("answer/tk/parList");
		
	}
	
	/**
	 * 弹出添加页面
	 * @param response
	 * @param request
	 * @return
	 */
	@RequestMapping("/toAddBank")
	public ModelAndView prepareAdd(@ModelAttribute TblQuestionBank bank,HttpServletResponse response, HttpServletRequest request){
		ModelAndView model = new ModelAndView();
	
		model.setViewName("answer/tk/addSt");
		return model;
	}
	
	
	/**
	 * 功能设置：添加
	 */
	@RequestMapping(value = "/addBank")	
	public ModelAndView addBank(TblQuestionBank record,HttpServletRequest request,HttpServletResponse response){
		ModelAndView mv=new ModelAndView();
		BJuiJSON bjui = new BJuiJSON();
		String typeId = request.getParameter("typeId");
		String answerId = request.getParameter("answerId");
		
		if(typeId=="3"){
			//判断题
			record.setType(typeId);
			record.setAnswer(answerId);
			record.setOptionc(null);
			record.setOptiond(null);
			record.setOptione(null);
			record.setOptionf(null);
		}else{
			record.setType(typeId);
			record.setAnswer(answerId);
		}
		try {
			tblQuestionBankService.insertSelective(record);
			
			bjui.setStatusCode("200");
			bjui.setMessage("添加成功！！！");
			bjui.setCloseCurrent(true);
			bjui.setTabid("navtab-tk");
		} catch (Exception e) {
			e.printStackTrace();				
			bjui.setStatusCode("300");
			bjui.setMessage("添加失败！！！");
		}
		String msg = JSONObject.fromObject(bjui).toString();
		mv.addObject("msg", msg);
		mv.setViewName("msg");
		return mv;
	}
	
	/**
	 * To参数设置
	 * @param bank
	 * @param response
	 * @param request
	 * @return
	 */
	@RequestMapping("/toSetPar")
	public ModelAndView toSetPar(@ModelAttribute TblQuestionBank bank,Model model,HttpServletResponse response, HttpServletRequest request){
	
//		String testid = request.getParameter("testid");
//		
//		model.addAttribute("testid",testid);

		return new ModelAndView("answer/tk/setPar");
	}
	/**
	 * 设置参数
	 * @param record
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/setPar")	
	public ModelAndView setPar(TblTestParameter record,HttpServletRequest request,HttpServletResponse response){
		ModelAndView mv=new ModelAndView();
		BJuiJSON bjui = new BJuiJSON();
		if (record==null) {
			bjui.setStatusCode("300");
			bjui.setMessage("请设置参数！");
		}else{
			try {
				record.setInsertdate(DateUtil.getCurrentDateAndTime());
				parameterService.insertSelective(record);
				         
				bjui.setStatusCode("200");
				bjui.setMessage("参数设置成功！");
				bjui.setCloseCurrent(true);
				bjui.setTabid("navtab-setpar");
			} catch (Exception e) {
				e.printStackTrace();				
				bjui.setStatusCode("300");
				bjui.setMessage("参数设置失败！！！");
			}
		}
		
		String msg = JSONObject.fromObject(bjui).toString();
		mv.addObject("msg", msg);
		mv.setViewName("msg");
		return mv;
	}
	
	@RequestMapping("/toImportSt")
	public ModelAndView toImportSt(){
		return new ModelAndView("answer/tk/importSt");
	}
	
	/**
	 * @return
	 */
	@RequestMapping("/importSt")
	public ModelAndView importSt(@RequestParam("xlsFile") CommonsMultipartFile xlsFile,HttpServletResponse response,HttpServletRequest request){
	System.out.println("----------------------");
		ModelAndView mv = new ModelAndView();
		BJuiJSON bjui = new BJuiJSON();
		
		String tempPath = System.getProperty("java.io.tmpdir");
		String fileName = xlsFile.getOriginalFilename();
		int position = fileName.lastIndexOf(".");
		String newFileName = tempPath + File.separator
				+ fileName.substring(0, position) + new Date().getTime()
				+ fileName.substring(position);
		int count = 0;
		if (!xlsFile.isEmpty()) {
			try {
				xlsFile.getFileItem().write(new File(newFileName));
				count = this.importSt(newFileName);
				
				System.out.println("----count------"+count);
				bjui.setStatusCode("200");
				bjui.setMessage("成功导入" + count + "条数据！");
				bjui.setCloseCurrent(true);
				bjui.setTabid("navtab-tk");
			} catch (Exception e) {
				e.printStackTrace();
				bjui.setStatusCode("300");
				bjui.setMessage("数据导入失败！");
			}
		}else{
			bjui.setStatusCode("300");
			bjui.setMessage("请确认数据文件内容是否为空！");
		}
		String msg = JSONObject.fromObject(bjui).toString();
		mv.addObject("msg",msg);
		mv.setViewName("msg");
		return mv;
	}
	
	private int importSt(String excelFile){
		InputStream is = null;
		Workbook wb = null;
		List<TblQuestionBank> list = new ArrayList<TblQuestionBank>();
		int count = 0;
		try {
			is = new FileInputStream(excelFile);
			wb = Workbook.getWorkbook(is);
			Sheet[] sheet = wb.getSheets();// 得到工作薄中的工作表

			for (int i = 0; i < sheet.length; i++) {
				Sheet st = sheet[i];
				if (st.getRows() > 0 && st.getColumns() > 0) {
					Cell cell = st.getCell(2, 1);// 得到工作表的第2行第3个单元格(x,y)
					String content = cell.getContents();
					if (content.equals("title")) {
					
						int k = 2;
						while (true) {
							if (k >= st.getRows()) {
								break;
							}
							content = cell.getContents();
							if (content == null) {
								// 如果单元格为空，则跳出循环
								break;
							}
							if (content.trim().equals("")) {
								// 如果单元格为空，则跳出循环
								break;
							}
							
							String type = st.getCell(1, k).getContents().trim(); // type
							String title = st.getCell(2, k).getContents().trim(); // title
							String optionA = st.getCell(3, k).getContents().trim(); // optionA
							String optionB = st.getCell(4, k).getContents().trim(); // optionB
							String optionC = st.getCell(5, k).getContents().trim(); // type
							String optionD = st.getCell(6, k).getContents().trim(); // type
							String optionE = st.getCell(7, k).getContents().trim(); // type
							String optionF = st.getCell(8, k).getContents().trim(); // type
							String answer = st.getCell(9, k).getContents().trim(); // answer
							String status = st.getCell(10, k).getContents().trim(); // status
							
							
							TblQuestionBank qb = new TblQuestionBank();
							
							qb.setType(type);
							qb.setTitle(title);
							qb.setOptiona(optionA);
							qb.setOptionb(optionB);
							qb.setOptionc(optionC);
							qb.setOptiond(optionD);
							qb.setOptione(optionE);
							qb.setOptionf(optionF);
							qb.setAnswer(answer);
							qb.setStatus(status);
							
							list.add(qb);
							
							k++;
						}
					}
				}
			}
		} catch (Exception e1) {
			e1.printStackTrace();
			throw new RuntimeException(e1);
		} finally {
			if (wb != null) {
				try {
					wb.close();// 关闭工作薄
				} catch (Exception e) {
					wb = null;
					e.printStackTrace();
				}
			}
			if (is != null) {
				try {
					is.close();// 关闭输入流
				} catch (Exception e) {
					is = null;
					e.printStackTrace();
				}
			}
		}
		count += tblQuestionBankService.importSt(list);
		return count;
	}
	
	
}
